package com.kotlin.demo.net

import org.json.JSONException
import retrofit2.HttpException
import retrofit2.Response
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * author : fang.zhang
 * e-mail : initzf@126.com
 * date   : 2019-12-04
 * desc   :
 */
class ApiResponse<T> {
    var code = SUCCESS_CODE
    var body: T? = null
    var msg: String? = null

    constructor(response: Response<T>) {
        body = response.body()
    }

    constructor(t: T) {
        body = t
    }

    constructor(throwable: Throwable) {
        body = null
        code = ERROR_CODE

        //对异常进行判断
        msg = when (throwable) {
            is SocketTimeoutException -> "超时"
            is HttpException -> {
                when (throwable.code()) {
                    404 -> "没有找到合适的资源"
                    500 -> "服务器内部错误"
                    else -> throwable.message()
                }
            }
            is JSONException -> "json解析异常"
            is UnknownHostException -> "网络异常"
            else -> throwable.message
        }
    }

    companion object {
        private const val TAG = "ApiResponse"

        const val ERROR_CODE = 99999

        const val SUCCESS_CODE = 200


        fun error(throwable: Throwable): ApiResponse<*> {
            return ApiResponse<Any?>(throwable)
        }
    }
}